package com.b2c.erp.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.b2c.common.utils.StringUtil;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.SystemRoleService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.entity.ManageUserEntity;
import com.b2c.interfaces.WmsUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：
 * 登录Controller
 *
 * @author qlp
 * @date 2018-12-26 5:37 PM
 */
@Controller
public class LoginController {
    @Autowired
    private WmsUserService manageUserService;
    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private ErpUserActionLogService logService;
    private static Logger log = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest request) {

        String ref = request.getParameter("ref");
        if (StringUtils.isEmpty(ref) == false && ref.equalsIgnoreCase("NULL")) ref = "";
        model.addAttribute("ref", ref);
        model.addAttribute("sjcd", "登录");
        return "login";
    }

    /**
     * 登录POST
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginPost(Model model, HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String ref = request.getParameter("ref");
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            model.addAttribute("ref", ref);
            model.addAttribute("username", username);
            model.addAttribute("error", "请输入");
            return "login";
        }

        ResultVo<ManageUserEntity> result = manageUserService.userLogin(username, password);
        if (result.getCode() == 0) {
            //添加session
//            HttpSession session = request.getSession();
            Integer userId = result.getData().getId();
//            session.setAttribute("userId", result.getData().getId());
//            session.setAttribute("userName", StringUtils.isEmpty(result.getData().getMobile())?result.getData().getUserName():result.getData().getMobile());
//            session.setAttribute("trueName", result.getData().getTrueName());
//            session.setAttribute("groupId", result.getData().getId());
            // System.out.println(manageUserService.checkUserPermissionMenu(userId,"aa"));
            /**初始化菜单**/
            manageUserService.initUserPermissionMenu(userId);

            //获取用户菜单
            var menuList = manageUserService.getUserPerMissionMenuByWMS(userId, 1);
//            session.setAttribute("menuList", menuList);
            //设置公用数据
            DataConfigObject.getInstance().setMenuList(menuList);
            DataConfigObject.getInstance().setLoginUserId(userId);
            DataConfigObject.getInstance().setLoginUserGroupId(result.getData().getGroupId());
            DataConfigObject.getInstance().setLoginUserName(result.getData().getUserName());

            systemRoleService.addManageUserLogin(userId, StringUtil.getLoalhostIP());

            log.info("用户登陆成功{userId:"+result.getData().getId()+",userName:"+username+",trueName:"+result.getData().getTrueName()+"}");
            //添加系统日志
            logService.addUserAction(userId, EnumUserActionType.Login,"/login","用户登录："+username,result.getMsg());


            //过期时间
            int expires = 7*24*60*60 * 1000;//7天
            Date expDate = new Date(System.currentTimeMillis() + expires);

            String secret = DataConfigObject.getInstance().getJwtSecret();
            //HMAC
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Map<String,Object> mapObj= new HashMap<>();
            var user = result.getData();
            mapObj.put("userId",user.getId());
            String token = JWT.create()
                    .withIssuer("auth0").withHeader(mapObj)
                    .withClaim("userId", user.getId())
                    .withClaim("userName", user.getUserName())
                    .withClaim("mobile", user.getMobile())
                    .withExpiresAt(expDate).withNotBefore(new Date())
                    .sign(algorithm);

            //将token发送给客户端
            Cookie cookie= new Cookie("token",token);
            response.addCookie(cookie);

            if (StringUtils.isEmpty(ref)) return "redirect:/";
            else return "redirect:" + ref;
        } else {
            model.addAttribute("ref", ref);
            model.addAttribute("username", username);
            model.addAttribute("error", result.getMsg());
            return "login";
        }



    }

    /**
     * 退出
     * @param request
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit(HttpServletRequest request,HttpServletResponse response) {
//        HttpSession session = request.getSession();
//        session.removeAttribute("userId");
//        session.removeAttribute("userName");
//        session.removeAttribute("trueName");
//        session.removeAttribute("menuList");
        //将token发送给客户端
        Cookie cookie= new Cookie("token","");
        response.addCookie(cookie);
        return "redirect:/";
    }
}
